#include <stdio.h>
#include <unistd.h> // 包含 usleep 和 sleep 函数
#include "ohos_init.h"
#include "cmsis_os2.h"
#include "los_swtmr.h"
#include "iot_gpio.h"
#include "iot_gpio_ex.h"
#include "iot_pwm.h"
#include "iot_errno.h"

#define BEEP_PORT 2


static const uint16_t g_tuneFreqs[] = {
    0,  
    4186, 
    4700, 
    5276, 
    5588, 
    6272, 
    7074,
    7902,
    3136, 
};

// 自定义音符
static const uint8_t g_scoreNotes[] = {
    1,2,3,1,    1,2,3,1,      3,4,5,3,4,5,
    5,6,5,4,3,1, 5,6,5,4,3,1, 1,8,1,1,8,1,
};

static const uint8_t g_scoreDurations[] = {
    4,4,4,4,  4,4,4,4,  4,4,8,4,4,8,
    3,1,3,1,4,4,  3,1,3,1,4,4,  4,4,8,4,4,8,
};

void BeepProcess(void) // 函数名修改为 BeepProcess
{
    unsigned int ret;
    unsigned int duty = 10;
    IoTGpioInit(BEEP_PORT);
    IoTGpioSetFunc(BEEP_PORT, IOT_GPIO_FUNC_GPIO_2_PWM2_OUT);
    IoTGpioSetDir(BEEP_PORT,IOT_GPIO_DIR_OUT);
    
    ret = IoTPwmInit(BEEP_PORT);
    if(ret != IOT_SUCCESS){
        printf("IoTPwmInit failed(%d)\n", BEEP_PORT);
        return;
    }
    while(1){
        printf("buzzerMusicTask start!\r\n");
        int count = sizeof(g_scoreDurations)/sizeof(g_scoreDurations[0]); 
        for(size_t i = 0; i < count; i++){ 
            uint32_t tune = g_scoreNotes[i];
            uint16_t freqDivisor  = g_tuneFreqs[tune]; 
            uint32_t tuneInterval = g_scoreDurations[i]*(125*1000);
            printf("%d %d %d %d\r\n",tune,(160*1000*1000)/freqDivisor,freqDivisor,tuneInterval);
            IoTPwmStart(BEEP_PORT,50, freqDivisor);
            usleep(tuneInterval);
            IoTPwmStop(BEEP_PORT);
            usleep(100000);
        }
        sleep(5); // 延时5秒
    }
}

APP_FEATURE_INIT(BeepProcess); 